package com.iplug.servlets;

import java.io.IOException;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

/**
 * @author Bora SAYINER
 */
@WebServlet("/loginservlet")
public class LoginServlet extends HttpServletBase {

    private static final long serialVersionUID = -3545325268646182348L;

    @Override
    protected void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (req.getRemoteUser() == null) {
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            boolean isErrorExist = checkLogin(username, password, req);
            if (!isErrorExist) {
                resp.sendRedirect("index.jsp");
                Logger.getLogger(LoginServlet.class).info(username + " login succesfully.");
            } else {
                req.getRequestDispatcher("login.jsp").forward(req, resp);
            }
        } else {
            req.logout();
            execute(req, resp);
        }
    }

    private boolean checkLogin(String username, String password, HttpServletRequest req) {
        boolean isErrorExist = false;
        HashMap<String, String> errorMap = new HashMap<String, String>();
        if (username == null || username.trim().length() == 0) {
            isErrorExist = true;
            errorMap.put("usernameError", "Kullanıcı Adı boş bırakılamaz.");
        }
        if (password == null || password.trim().length() == 0) {
            isErrorExist = true;
            errorMap.put("passwordError", "Parola boş bırakılamaz");
        }
        if (!isErrorExist) {
            try {
                req.login(username, password);
            } catch (ServletException exception) {
                isErrorExist = true;
                errorMap.put("loginError", "Giriş başarısız. Lütfen bilgilerinizi kontrol ediniz.");
                Logger.getLogger(LoginServlet.class).warn("Login failed.", exception);
            }
        }
        if (isErrorExist) {
            req.setAttribute("errorMap", errorMap);
        }
        return isErrorExist;
    }
}
